from repositories.product_repo import ProductRepo
from utils import upload_file, delete_file
from config import Config


class ProductService:
    category = 'products'  # 文件存储分类

    @staticmethod
    def add( name, desc, category, quality, specification, file):
        # 上传图片文件
        filename = upload_file(file, ProductService.category)

        # 创建产品对象
        product_data = {
            'name': name,
            'url': filename,
            'desc': desc,
            'category': category,
            'quality': quality,
            'specification': specification
        }

        # 保存到数据库
        ProductRepo.insert(product_data)
        return filename

    @staticmethod
    def get_products_for_api():
        items = ProductRepo.find_by_paginated(1, 99)
        print(items['data'])
        print("ProductService", ProductService.category)
        return [
            'http://127.0.0.1:8000/uploads/' + ProductService.category + '/' + item.url
            for item in items['data']
        ]

    @staticmethod
    def list(page, pagesize=Config.PAGE_SIZE):
        # 获取分页数据
        data = ProductRepo.find_by_paginated(page, pagesize)

        # 计算总页数
        total_pages = (data['total'] + pagesize - 1) // pagesize

        # 处理图片URL路径
        new_data = [
            {
                'id': item.id,
                'name': item.name,
                'url': f"/{Config.UPLOAD_FOLDER}/{ProductService.category}/{item.url}",
                'desc': item.desc,
                'quality': item.quality,
                'category': item.category,
                'specification': item.specification
            }
            for item in data.get('data')
        ]

        return {
            'data': new_data,
            'total': data['total'],
            'total_pages': total_pages,
            'page': page,
            'pagesize': pagesize
        }

    @staticmethod
    def delete_by_id(id):
        product = ProductRepo.find_by_id(id)
        if product:
            # 删除物理文件
            delete_file(product.url, ProductService.category)
            # 删除数据库记录
            ProductRepo.delete_by_id(id)
            return True
        return False

    @staticmethod
    def update(id, name, desc, category, quality, specification, file=None):
        product = ProductRepo.find_by_id(id)
        if not product:
            raise ValueError("产品不存在")

        if file:
            # 删除旧图片
            delete_file(product.url, ProductService.category)
            # 上传新图片
            filename = upload_file(file, ProductService.category)
            product.url = filename

        update_data = {
            'name': name,
            'desc': desc,
            'category': category,
            'quality': quality,
            'specification': specification
        }
        ProductRepo.update(product, update_data)